package cmd

import (
	"context"
	v1 "mygf2/api/v1"
	"mygf2/internal/controller"
	"mygf2/library"
	"net/http"
	"strings"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"
)

func MiddlewareCORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}
func MiddlewareAuth(r *ghttp.Request) {
	token := r.GetHeader("Authorization")
	token = strings.Replace(token, "Bearer ", "", 1)
	if token == "" {
		r.Response.WriteStatusExit(http.StatusForbidden)
	}
	v, err := library.GlobalCache.Get(r.Context(), token)
	g.Redis().Do(r.Context(), "SET", "cache1", v)
	//fmt.Println(v)
	if err != nil {
		r.Response.WriteStatusExit(http.StatusForbidden)
	}
	//没有缓存
	if v.IsEmpty() {
		r.Response.WriteStatusExit(http.StatusForbidden)
	}
	var user v1.ThirdServiceUserDataRes
	if err = v.Scan(&user); err != nil {
		panic(err)
	}
	r.SetCtxVar("user-info", user)
	r.SetCtxVar("token", token)

	r.Middleware.Next()

}

var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			s := g.Server()
			s.BindStatusHandler(404, func(r *ghttp.Request) {
				r.Response.Writeln("This is customized 404 page")
			})
			//s.Use(MiddlewareCORS)
			s.Group("/v1", func(group *ghttp.RouterGroup) {
				group.Middleware(MiddlewareCORS, ghttp.MiddlewareHandlerResponse)
				//不需要登录的
				//group.Bind(controller.User.Login)
				group.GET("/hello", controller.Hello.Hello)
				group.POST("/login", controller.User.Login)
				group.Group("/", func(group *ghttp.RouterGroup) {
					//授权验证
					//group.Middleware(MiddlewareAuth)
					group.GET("/auth/me", controller.User.GetUserInfo)
					group.POST("/auth/logout", controller.User.Logout)
					group.GET("/getSourceList", controller.Video.GetSourceList)
					group.POST("/analysisUrl", controller.Video.AnalysisUrl)
					group.POST("/gather/douyinByAuthor", controller.Video.DouyinByAuthor)
					group.GET("/gather/list", controller.Video.GetList)
					group.GET("/gather/listCount", controller.Video.GetListCount)
					group.POST("/gather/download", controller.Video.Download)
					group.POST("/gather/inStorage", controller.Video.InStorage)
					group.POST("/gather/info", controller.Video.GetItem)
				})
				// group.Bind(
				// 	controller.Hello,
				// )
			})
			s.EnableAdmin("/manager/Gt45533jj34f5")
			s.Run()
			return nil
		},
	}
)
